#include <QDebug>
#include <QVideoFrame>

#include "yuvloader.h"

YUVLoader::YUVLoader(QObject *parent)
    : QObject(parent),
      m_file("../VideoOutput/test_yuv420p_320x180.yuv"),
      m_stream(&m_file)
{
    if(!m_file.open(QIODevice::ReadOnly)){
        qDebug() << "open file failed:" << m_file.errorString();
    }
    connect(&m_frameTimer, &QTimer::timeout, this, &YUVLoader::onFrameTimer);
    m_frameTimer.start(33);
}

void YUVLoader::onFrameTimer() {
    int width = 320;
    int height = 180;
    const int frameSize = int(320*180*1.5);

    QVideoFrame frame(frameSize, QSize(width, height), width, QVideoFrame::Format_YUV420P);
    if (frame.map(QAbstractVideoBuffer::WriteOnly)) {
        int readSize = m_stream.readRawData((char*)frame.bits(), frameSize);
        if (readSize != frameSize) {
            m_stream.device()->seek(0);
            m_stream.readRawData((char*)frame.bits(), frameSize);
        }
        frame.unmap();
        emit newFrameAvailable(frame);
    }
}

YUVLoader::~YUVLoader() {
    m_file.close();
}
